const {
	isObject,
	isArray
} = Require("utils.libs.src.dao-type");
const {
	hasOwn
} = Require("utils.libs.src.dao-object");

const isSnakeCase = /_(\w)/g;
const isCamelCase = /[A-Z]/g;

function snake2camel(value) {
	return value = value.replace(isSnakeCase, (_, c) => (c ? c.toUpperCase() : ''));
}

function camel2snake(value) {
	//首字母不转换@@@微信第三方平台接口返回的参数首字母是大写，所以这里需要排除首字母
	return value.replace(/^[A-Z]/, str => str.toLowerCase()).replace(isCamelCase, str => '_' + str.toLowerCase())
	// return value.replace(isCamelCase, str => '_' + str.toLowerCase())
}

function parseObjectKeys(obj, type) {
	let parserReg, parser
	switch (type) {
		case 'snake2camel':
			parser = snake2camel
			parserReg = isSnakeCase
			break
		case 'camel2snake':
			parser = camel2snake
			parserReg = isCamelCase
			break
	}
	for (const key in obj) {
		if (hasOwn(obj, key)) {
			let keyCopy = key;
			if (parserReg.test(key)) {
				keyCopy = parser(key)
			}
			if (type == 'snake2camel') {
				keyCopy = keyCopy.slice(0, 1).toUpperCase() + keyCopy.slice(1);
			}
			obj[keyCopy] = obj[key]
			delete obj[key]
			if (isObject(obj[keyCopy])) {
				obj[keyCopy] = parseObjectKeys(obj[keyCopy], type)
			} else if (isArray(obj[keyCopy])) {
				obj[keyCopy] = obj[keyCopy].map((item) => {
					return parseObjectKeys(item, type)
				})
			}
		}
	}
	return obj
}
// 蛇形转换成驼峰
function snake2camelJson(obj) {
	return parseObjectKeys(obj, 'snake2camel')
}
// 驼峰转换成蛇形
function camel2snakeJson(obj) {
	return parseObjectKeys(obj, 'camel2snake')
}

module.exports = {
	snake2camelJson,
	camel2snakeJson
};
